package com.example.housingRentalSystem.controller;

import com.example.housingRentalSystem.bean.User;
import com.example.housingRentalSystem.security.provider.JwtTokenProvider;
import com.example.housingRentalSystem.service.Impl.UserServiceImpl;
import com.example.housingRentalSystem.utils.ApiResponse;
import com.example.housingRentalSystem.utils.HttpStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 王硕
 * @version jdk21
 * @className UserController
 * @description
 * @date 2025/3/20 16:34
 */
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户管理")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private UserServiceImpl userService;

    private String getTokenFromHeader(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            if (jwtTokenProvider.validateToken(token)) {
                return token;
            }
        }
        return null;
    }
    @GetMapping("/user-info")
    @ApiOperation(value = "获取用户信息", notes = "返回不包含敏感信息的用户数据")
    public ApiResponse<User> getUserInfo(HttpServletRequest request) {
        String token = getTokenFromHeader(request);
        String username = jwtTokenProvider.getUsernameFromToken(token);

        User user = userService.findUserInfoByAccount(username);
        return ApiResponse.success(user);
    }

    @PostMapping("/updateUserInfo")
    public ApiResponse<String> updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        try {
            if (user.getAccount() == null) {
                return ApiResponse.error(HttpStatus.BAD_REQUEST.getCode(), "账户不能为空");
            }
            String token = getTokenFromHeader(request);
            if (token != null) {
                System.out.println("接收Token: " + token);
                System.out.println("Token是否有效: " + jwtTokenProvider.validateToken(token));
            }
            String account = jwtTokenProvider.getUsernameFromToken(token);
            System.out.println("当前操作用户: " + account);
            user.setAccount(account);

            if (user.getIdcard() == null) {
                user.setIdcard(userService.findUserInfoByAccount(account).getIdcard());
            }

            userService.updateUserInfo(user);
            return ApiResponse.success("个人信息更新成功");
        } catch (RuntimeException e) {
            logger.error("个人信息更新失败: {}", e.getMessage(), e);
            return ApiResponse.error(HttpStatus.BAD_REQUEST.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("个人信息更新失败: {}", e.getMessage(), e);
            return ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), "个人信息更新失败");
        }
    }

    @GetMapping("/byRole/{roleName}")
    public ApiResponse<List<User>> getUsersByRole(
            @PathVariable String roleName) {
        try {
            List<User> users = userService.getUsersByRole(roleName);
            return ApiResponse.success(users);
        } catch (Exception e) {
            logger.error("获取用户列表失败: {}", e.getMessage(), e);
            return ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), "获取用户列表失败");
        }
    }

    @PostMapping("/disable-user")
    public ApiResponse<String> disableUser(@RequestBody Map<String, Object> request) {
        try {
            Integer userId = (Integer) request.get("userId");
            Integer status = (Integer) request.get("status");
            userService.updateUserStatus(userId, status);
            return ApiResponse.success("操作成功");
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    @PostMapping("/reset-password")
    public ApiResponse<String> resetPassword(@RequestBody Map<String, Object> request) {
        try {
            Integer userId = (Integer) request.get("userId");
            userService.resetPassword(userId);
            return ApiResponse.success("密码已重置为123456");
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    @GetMapping("/selectUserCount")
    public ApiResponse<Integer> selectUserCount() {
            int count = userService.selectUserCount();
            return ApiResponse.success(count);
    }
}
